from sqlalchemy.orm import Session
from app.models.attachment import Attachment
from app.schemas.attachment import AttachmentCreate
from typing import List, Optional
import os

# 获取附件通过ID
def get_attachment(db: Session, attachment_id: int):
    return db.query(Attachment).filter(Attachment.id == attachment_id).first()

# 获取实体的所有附件
def get_attachments_by_entity(db: Session, entity_type: str, entity_id: int):
    return db.query(Attachment).filter(
        Attachment.entity_type == entity_type,
        Attachment.entity_id == entity_id
    ).all()

# 创建附件
def create_attachment(db: Session, attachment: AttachmentCreate, uploaded_by: int):
    db_attachment = Attachment(
        filename=attachment.filename,
        original_filename=attachment.original_filename,
        file_path=attachment.file_path,
        file_size=attachment.file_size,
        mime_type=attachment.mime_type,
        entity_type=attachment.entity_type,
        entity_id=attachment.entity_id,
        uploaded_by=uploaded_by
    )
    db.add(db_attachment)
    db.commit()
    db.refresh(db_attachment)
    return db_attachment

# 删除附件
def delete_attachment(db: Session, attachment_id: int):
    db_attachment = db.query(Attachment).filter(Attachment.id == attachment_id).first()
    if db_attachment:
        # 删除文件
        try:
            if os.path.exists(db_attachment.file_path):
                os.remove(db_attachment.file_path)
        except Exception as e:
            print(f"删除文件失败: {e}")
        
        # 删除数据库记录
        db.delete(db_attachment)
        db.commit()
    return db_attachment

# 根据实体删除所有附件
def delete_attachments_by_entity(db: Session, entity_type: str, entity_id: int):
    attachments = get_attachments_by_entity(db, entity_type, entity_id)
    for attachment in attachments:
        delete_attachment(db, attachment.id)
    return len(attachments)